package net.kuratkoo.jidelnicekvut;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ListActivity implements AdapterView.OnItemClickListener {

    private static final String TAG = "JidelnicekVUT|MainActivity";
    private CanteenSet canteenSet;
    private ProgressBar progress;
    private LinearLayout loading;
    private TextView empty;
    private ImageView help;
    
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.activity_main);

        PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

        Log.d(TAG, "====================== " + getText(R.string.app_name) + " ======================");

        progress = (ProgressBar) findViewById(R.id.actionbar_progress);
        loading = (LinearLayout) findViewById(R.id.loading);
        empty = (TextView) findViewById(R.id.empty);
        help = (ImageView) findViewById(R.id.help);

        getListView().setOnItemClickListener(this);

        canteenSet = new CanteenSet(this);
        canteenSet.getAll();

        if (canteenSet.isEmpty()) {
            new RefreshAsyncTask().execute();
        } else {
            setListAdapter(new CanteenListAdapter(this, canteenSet));
        }

        help.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                Builder ad = new AlertDialog.Builder(MainActivity.this);
                ad.setTitle(getText(R.string.tips));
                ad.setIcon(android.R.drawable.ic_dialog_info);
                ad.setMessage(getText(R.string.tips_text));
                ad.show();
            }
        });

        registerForContextMenu(getListView());
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
        menu.setHeaderTitle(this.canteenSet.get(info.position).name);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.context_menu_canteen_list, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        String uri = null;
        switch (item.getItemId()) {
            case R.id.show_on_map:
                try {
                    uri = "geo:0,0?q=" + this.canteenSet.get(info.position).address;
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(uri)));
                } catch (ActivityNotFoundException ante) {
                    Toast.makeText(this, getText(R.string.intent_not_found), Toast.LENGTH_LONG).show();
                }
                return true;
            case R.id.foursquare:
                try {
                    uri = "http://m.foursquare.com/search?q=" + this.canteenSet.get(info.position).name;
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(uri)));
                } catch (ActivityNotFoundException ante) {
                    Toast.makeText(this, getText(R.string.intent_not_found), Toast.LENGTH_LONG).show();
                }
                return true;
            case R.id.opening_hours:
                Builder ad = new AlertDialog.Builder(MainActivity.this);
                ad.setTitle(this.canteenSet.get(info.position).name);
                ad.setMessage(this.canteenSet.get(info.position).getFormatedOpeningHours());
                ad.show();
                return true;
            case R.id.share:
                Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
                shareIntent.setType("text/plain");
                shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getText(R.string.app_name) + " - " + this.canteenSet.get(info.position).name);
                shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, getText(R.string.share_text_1) + " " + this.canteenSet.get(info.position).name + "! " + getText(R.string.share_text_2));
                startActivity(Intent.createChooser(shareIntent, getText(R.string.choose_one)));
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options_menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.preferences:
                startActivity(new Intent(this, Preferences.class));
                return true;
            case R.id.refresh:
                this.goRefresh();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (canteenSet != null) {
            canteenSet.getAll();
            ((CanteenListAdapter) getListAdapter()).notifyDataSetChanged();
        }
        
        if (canteenSet.isEmpty()) {
            getListView().setVisibility(View.GONE);
            empty.setVisibility(View.VISIBLE);
        } else {
            getListView().setVisibility(View.VISIBLE);
            empty.setVisibility(View.GONE);
        }
    }

    public void goRefresh() {
        AlertDialog.Builder ad = new AlertDialog.Builder(this);
        ad.setMessage(getText(R.string.are_you_sure_to_refresh));
        ad.setCancelable(true);
        ad.setPositiveButton(getText(R.string.yes), new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int id) {
                new RefreshAsyncTask().execute();
            }
        });
        ad.setNegativeButton(getText(R.string.no), new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
        ad.show();
    }

    public void onItemClick(AdapterView<?> arg0, View view, int i, long _id) {
        startActivity(new Intent(MainActivity.this, DetailActivity.class).putExtra("canteenId", (int) _id));
    }

    private class RefreshAsyncTask extends AsyncTask<Void, Void, Boolean> {

        @Override
        protected void onPreExecute() {
            progress.setVisibility(View.VISIBLE);
            loading.setVisibility(View.VISIBLE);
            getListView().setVisibility(View.GONE);
            empty.setVisibility(View.GONE);
        }

        @Override
        protected Boolean doInBackground(Void... arg0) {
            try {
                CanteenSet.sync(MainActivity.this);
                canteenSet.getAll();
            } catch (Exception ex) {
                Log.e(TAG, "Error: " + ex.getLocalizedMessage());
                return false;
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            progress.setVisibility(View.GONE);
            loading.setVisibility(View.GONE);
            if (result) {
                if (!canteenSet.isEmpty()) {
                    getListView().setVisibility(View.VISIBLE);
                    canteenSet.getAll();
                    ((CanteenListAdapter) getListAdapter()).notifyDataSetChanged();
                } else {
                    empty.setVisibility(View.VISIBLE);
                }
            } else {
                Toast.makeText(MainActivity.this, getString(R.string.unable_to_load_canteen_list), Toast.LENGTH_LONG).show();
            }
        }
    }

    public void goAbout(View view) {
        try {
            Builder ad = new AlertDialog.Builder(this);
            ad.setTitle(getString(R.string.app_name) + " v" + getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
            ad.setIcon(R.drawable.ic_launcher);
            LayoutInflater li = LayoutInflater.from(this);
            View about = li.inflate(R.layout.view_about, null);
            ad.setView(about);
            ((ImageView) about.findViewById(R.id.donate)).setOnClickListener(new View.OnClickListener() {
                public void onClick(View arg0) {
                    String uri = Constants.DONATE_URL;
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(uri)));
                }
            });
            ad.show();
        } catch (NameNotFoundException ex) {
            Log.e(TAG, "Error: " + ex.getLocalizedMessage());
        }
    }
}
